﻿<style type="text/css">

* { margin: 0; padding: 0; }

html { height: 100%; font-size: 62.5% }

@*body { height: 100%; background-color: #FFFFFF; font: 1.2em Verdana, Arial, Helvetica, sans-serif; }*@


/* ==================== Form style sheet ==================== */

.form_addproduct { margin: 25px 0 0 29px; width: 445px; padding-bottom: 30px }
form * { vertical-align: middle; }

fieldset { margin: 0 0 22px 0; border: 0; }
legend { font-size: 1.2em; color: #2E6600; font-weight: bold; }

label { float: left; display: block; width: 100px; margin-top: 4px; clear: left; }
label.choose { width: 162px; }
label.spam-protection { display: inline; width: auto; }

input.text, textarea, input.choose, input.answer { border: 1px solid #909090; padding: 3px; }
input.text { width: 300px; margin: 0 0 8px 0; }
textarea { width: 400px; margin: 0 0 12px 0; display: block; }

select { width: 250px; border: 1px solid #909090; padding: 2px;  margin: 0 0 8px 0; }

input.choose { margin: 0; }
input.answer { width: 40px; margin: 0 0 0 10px; }
input.submit-text { font: 1.4em Georgia, "Times New Roman", Times, serif; letter-spacing: 1px; display: block; margin: 23px 0 0 0; float: left}

hr.formik { height: 1px; color: gray; background-color: gray; border: 0 solid gray; margin: 3px 0 20px 0; }
form br { display: none; }

input.choose {
    margin: 0 2px 0 0;
}
input.inp-text, textarea, input.choose, input.answer {
    border: 1px solid #909090;
    padding: 3px;
}
/* ==================== Form style sheet END ==================== */

</style>


<div style="overflow: hidden">
	@if (ViewBag.id != 0)
	{
		<h1 style="text-align: center">Thay đổi thông tin sản phẩm</h1>
		<input id="shiny" type="button" value="Xem" style="float:right" onclick="javascript:window.location.href='/home/viewproduct/@ViewBag.id';return false;"/>
	}
 else
 {
	 <h1 style="text-align: center">Thêm sản phẩm</h1>
	 <ul>
		 <li> <a data-bind="click:addColor" > + Thêm Màu</a></li>
		 <li> <a data-bind="click:addBrand" > + Thêm Thương Hiệu</a></li>
	 </ul>
 }
	
	<section  class="right fl" data-bind="foreach: products">
		<br><br>
		<label  style="width: 150px; clear: none"><input type="radio" value="Mobile" data-bind="checked: $root.Type" />Điện Thoại</label>
		<label  style="width: 150px; clear: none"><input type="radio" value="Tablet" data-bind="checked: $root.Type" />Máy Tính Bảng</label>
		<label  style="width: 150px; clear: none"><input type="radio" value="PhuKien" data-bind="checked: $root.Type"/>Phụ Kiện</label>
		<form action="" method="post" style="margin-top: 30px" class="form_addproduct">
			<!-- ============================== Fieldset 1 ============================== -->
			<fieldset>
				<legend>Thông tin Sản Phẩm:</legend>
				<hr class="formik" />

				<label for="input-one"><strong>Tên sản phẩm:</strong></label><br />
				<input name="input-one-name" type="text" size="20" id="input-one" class="text"  data-bind="value: Name"/><br />
				
				@if (ViewBag.id != 0)
				{
					<label for="input-one"><strong>Mã sản phẩm:</strong></label><br />
					<input name="input-one-name" type="text" size="20" id="input-one" class="text"  data-bind="value: ProductId" disabled/><br />	
				}
	
				<label for="input-one" class="choose">Màu:</label><br />
				<select id="select2" name="select2" data-bind="options: $root.colors, value:Color"></select>
				
				<label for="input-one" class="choose">Thương hiệu: </label><br />
				<select id="select2" name="select2" data-bind="options: $root.brands, value : Brand"></select>
				
				<label for="optionblock" style="width: 300px; margin-left: 100px;">
					<input id="optionblock" class="choose" type="checkbox" value="1" name="option[]" data-bind="checked: Block">
					Block
				</label>

				<label for="input-two"><strong>Hình ảnh:</strong></label><br />
				<input name="input-two-name" type="text" size="20" id="input-two" class="text"  data-bind="value:Image"/>
				
@*				<label for="input-two"><strong>Số lượng:</strong></label><br />
				<input name="input-two-name" type="text" size="20" id="input-two" class="text" data-bind="value:Quantity"/>*@
				
				<label for="input-two"><strong>Giá:</strong></label><br />
				<input name="input-two-name" type="text" size="20" id="input-two" class="text" data-bind="value:Price"/>
				
				<label for="input-two"><strong>Giá bán:</strong></label><br />
				<input name="input-two-name" type="text" size="20" id="input-two" class="text" data-bind="value:ActualCost"/>
				
				<label for="input-two"><strong>Bảo hành:</strong></label><br />
				<input name="input-two-name" type="text" size="20" id="input-two" class="text" data-bind="value:Warranty"/>
				
				<label for="option1" style="width: 300px; margin-left: 100px;">
					<input id="option1" class="choose" type="checkbox" value="1" name="option[]" data-bind="checked: Promotion">
					Khuyến mãi
				</label>
				
				<label for="option2" style="width: 300px; margin-left: 100px;">
					<input id="option2" class="choose" type="checkbox" value="1" name="option[]" data-bind="checked: IsUsed">
					Đã qua xử dụng
				</label>
				
				<label for="option3" style="width: 300px; margin-left: 100px;">
					<input id="option3" class="choose" type="checkbox" value="1" name="option[]" data-bind="checked: CommingSoon">
					Sắp về
				</label>
				
				<label for="option4" style="width: 300px; margin-left: 100px;">
					<input id="option4" class="choose" type="checkbox" value="1" name="option[]" data-bind="checked: Arrive">
					Mới về
				</label>	
				<p><input type="button" alt="SUBMIT" name="Submit" value="Lưu" class="submit-text" data-bind="click: $root.submit"/></p>
			</fieldset>
		</form>

	</section>


	<section class="right fl">
			<fieldset>
		<legend>Thông tin Khuyến Mãi/Cấu Hình:</legend>
			<hr class="formik" />
			<a data-bind="click:toggleKhuyenMai" href="#">Ẩn/Hiện nội dung</a>
			<div id="khuyenmai_content">	
				<textarea id ="khuyenmai_content_value" style="height: 300px" data-bind="value : Promotion"></textarea>
				<p style="float: right"><input type="button" alt="SUBMIT" name="Submit" value="Lưu" class="submit-text" data-bind="click: sendPromotion"/></p>
			</div>
		</fieldset>
		<br>
		<fieldset>
			<legend>Thông tin Chi Tiết:</legend>
			<hr class="formik" />
			<a data-bind="click:toggleDetail" href="#">Ẩn/Hiện nội dung</a>
			<div id="detail_content">
				<textarea id="detail_content_value" style="height: 500px" data-bind="value : Detail"></textarea>
				<p style="float: right"><input type="button" alt="SUBMIT" name="Submit" value="Lưu" class="submit-text" data-bind="click: sendDetail"/></p>
			</div>
		</fieldset>
	</section>
	@if (ViewBag.id != 0)
	{
		<input id="shiny" type="button" value="Xem" style="float:right" onclick="javascript:window.location.href='/home/viewproduct/@ViewBag.id';return false;"/>
	}
	
	


</div>




<script src="../../Scripts/knockout-3.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.validation.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.fancybox.js" type="text/javascript"></script>
<script src="../../Scripts/message.js" type="text/javascript"></script>
<script src="../../Scripts/Models/Product.js" type="text/javascript"></script>
<link href="../../Content/themes/message_default.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/numeral.min.js" type="text/javascript"></script>
<script src="../../Scripts/tinymce/tinymce.min.js" type="text/javascript"></script>
<script src="../../Scripts/Models/Promotion.js" type="text/javascript"></script>
<script type="text/javascript">
	// init Detail Editor
	tinymce.init({
		selector: "textarea",
		theme: "modern",
		plugins: [
			"advlist autolink lists link image charmap print preview hr anchor pagebreak",
			"searchreplace wordcount visualblocks visualchars code fullscreen",
			"insertdatetime media nonbreaking save table contextmenu directionality",
			"emoticons template paste textcolor"
		],
		toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
		toolbar2: "print preview media | forecolor backcolor emoticons",
		image_advtab: true,
		templates: [
			{ title: 'Test template 1', content: 'Test 1 butin' },
			{ title: 'Test template 2', content: 'Test 2' }
		]
	});
	
	function ProductDataModel() {
		// Data
		var self = this;
		self.products = ko.observableArray();
		self.colors = ko.observableArray(['Đỏ', 'Đen', 'Trắng', 'Hồng', 'Vàng']);
		self.brands = ko.observableArray(['Apple', 'LG', 'Nokia', 'HTC', 'Sony','SamSung', 'Sky','BlackBerry','Oppo', 'Nexus','GiONNE','Motorola','Casio','Asus','Acer','Microsoft']);
		self.Promotion = ko.observable();
		self.Detail = ko.observable();
		self.Type = ko.observable("Mobile");

		var proId = @ViewBag.id;
		if (proId > 0) {
			$.getJSON("/api/products/GetProduct/@ViewBag.id", function(allData) {
				self.products.removeAll();
				self.products.push(new Product(allData.Product));
			if (allData.Promotion != null)
				self.Promotion(allData.Promotion.Content);
			if (allData.Detail != null)
				self.Detail(allData.Detail.Content);
			});
		} else {
			self.products.push(new Product({
			Name: "",
			Color: "Đen",
			Quanlity: 10,
			Brand: "LG",
			Quantity: 10,
			Price: 11590000,
			ActualCost: 10950000,
			Warranty: 12,
			Promotion: true,
			IsUsed: true,
			CommingSoon: true,
			IsDelete: false,
			Type:1
		}));
		}
		
		//GEt color
		$.getJSON("/api/products/GetColor", function(allData) {
			self.colors(allData);
		});
		
		//GEt brand
		$.getJSON("/api/products/GetBrand", function(allData) {
			self.brands(allData);
		});

		var curId = '';
		self.submit = function (product) {
            var errors = ko.validation.group(product);
            var hasErrors = errors().length!=0;
             if(hasErrors){
                dhtmlx.alert({
						    type: "alert-error",
						    text: "Dữ liệu nhập thiếu hoặc sai quy định",
						    title: "Cảnh báo!",
						    ok: "OK"
					    });
             }else{
                var type = 2;
			    if (self.Type() == "Mobile")
				    type = 1;
			    else if(self.Type() == "Tablet")
				    type = 3;
			    product.Type(type);
			    var action_url = '/api/Products/PostProduct';
			    var type = 'POST';
			    var action_text = "Thêm: \"";
			    if (proId > 0)
			    {	
				    action_url = '/api/Products/PutData';
				    type = 'PUT';
				    action_text = "Sửa: \"";
			    }
			
			    // unformat price
			    product.Price( numeral().unformat('$' + product.Price()) );
			    product.ActualCost( numeral().unformat('$' + product.ActualCost()));

			    var json = ko.toJSON(product);
			    $.ajax({
				    url: action_url,
				    type: type,
				    contentType: "application/json; charset=utf-8",
				    context: {productname: product.Name(), action : action_text, id:product.ProductId()},
				    data: json,
				    success: function(results, status) {
					    if (status == "success") {
						    //asign id to current product
						    curId = results.ProductId;
						    self.products.removeAll();
						    self.products.push(new Product(results));
						    dhtmlx.alert({
							    text: this.action + results.Name + "\" thành công!",
							    title: "Thành Công!",
							    ok: "OK",
							    callback: function (result) {
								    window.location.href = '/home/EditProduct/' + curId;
						    }
						    });
					    }
				    },
				    error: function(results, status) {
					    dhtmlx.alert({
						    type: "alert-error",
						    text: this.action + this.productname + " thất bại",
						    title: "Thất Bại!",
						    ok: "OK"
					    });
				    }
			    });
             }
			
		};



		self.sendPromotion = function () {
			var promotionStr = window.parent.tinymce.get('khuyenmai_content_value').getContent();
			var promotion = new Promotion(promotionStr, self.products()[0]);
			var json = ko.toJSON(promotion);
			$.ajax({
				url: '/api/Products/PostPromotion',
				type: 'POST',
				contentType: "application/json; charset=utf-8",
				context: promotion,
				data: json,
				success: function (results, status) {
					if (status == "success") {
						dhtmlx.alert({
							text: "Thêm: Thông tin khuyến mãi thành công!",
							title: "Thành Công!",
							ok: "OK"
						});
					}
				},
				error: function (results, status) {
					dhtmlx.alert({
						type: "alert-error",
						text: "Thêm: Thông tin khuyến mãi thất bại <br>Lỗi:" + results.responseText,
						title: "Thất Bại!",
						ok: "OK"
					});
				}
			});
		};

		self.sendDetail = function () {
			var detailStr = window.parent.tinymce.get('detail_content_value').getContent();
			var detai = new Detail(detailStr, self.products()[0]);
			var json = ko.toJSON(detai);
			$.ajax({
				url: '/api/Products/PostDetail',
				type: 'POST',
				contentType: "application/json; charset=utf-8",
				context: detai,
				data: json,
				success: function (results, status) {
					if (status == "success") {
						dhtmlx.alert({
							text: "Thêm: Thông tin sản phẩm thành công!",
							title: "Thành Công!",
							ok: "OK"
						});
					}
				},
				error: function (results, status) {
					dhtmlx.alert({
						type: "alert-error",
						text: "Thêm: Thông tin sản phẩm thất bại <br>Lỗi:" + results.responseText,
						title: "Thất Bại!",
						ok: "OK"
					});
				}
			});
		};

		self.toggleKhuyenMai = function() {
			$("#khuyenmai_content").slideToggle();
		};

		self.toggleDetail = function () {
			$("#detail_content").slideToggle();
		};

		$("#khuyenmai_content").hide();
		$("#detail_content").hide();

		self.addBrand = function() {
				var box = dhtmlx.modalbox({ 
				title:"Nhập thêm Thương Hiệu", 
				text:"<div id='form_in_box'><div><label><input id='newbrand' class='inform' type='text' style=\"width: 260px; padding: 6px 4px;\"></label></div><div></div><div></div><div><span class='dhtmlx_button'><input type='button' value='Lưu' onclick='save_callback(this)' style='width:250px;'></span></label></div></div>",
				width:"250px"
			});
			//timeout is necessary only in IE
			setTimeout(function(){
				box.getElementsByTagName("input")[0].focus();	
			},1);
		};
		
		self.addColor = function() {
				var box = dhtmlx.modalbox({ 
				title:"Nhập thêm Màu", 
				text:"<div id='form_in_box'><div><label><input id='newcolor' class='inform' type='text' style=\"width: 260px; padding: 6px 4px;\"></label></div><div></div><div></div><div><span class='dhtmlx_button'><input type='button' value='Lưu' onclick='save_callback2(this)' style='width:250px;'></span></label></div></div>",
				width:"250px"
			});
				//timeout is necessary only in IE
				setTimeout(function(){
					box.getElementsByTagName("input")[0].focus();	
				},1);
			};

		self.sendAddColor = function(color) {
			$.getJSON("/api/products/GetPutColor/"+color, function(allData) {
			});
		};
		
		self.sendAddBrand = function(brand) {
			$.getJSON("/api/products/GetPutBrand/"+brand, function(allData) {
			});
		};
	}

	var viewModel = new ProductDataModel();
	ko.applyBindings(viewModel);
	
	function save_callback(box) {
		var v = $("#newbrand").val();
		viewModel.sendAddBrand(v);
		viewModel.brands.push(v);
		dhtmlx.modalbox.hide(box);
		
	}
	
	function save_callback2(box) {
		var v = $("#newcolor").val();
		viewModel.sendAddColor($("#newcolor").val());
		viewModel.colors.push(v);
		dhtmlx.modalbox.hide(box);
	}

</script>